<?php

namespace App\Validators\System;

use App\Validators\PassesValidator;
use Illuminate\Support\Facades\Input;
use \Prettus\Validator\Contracts\ValidatorInterface;
use \Prettus\Validator\LaravelValidator;

class PermissionValidator extends LaravelValidator
{
    use PassesValidator;
    protected $rulesMessages=[
        'name.required' => '权限标识是必填的',
        'name.unique' => '权限标识已经存在',
        'display_name.required' => '资源名称是必填的',
        'parent_id.required' => 'parent_id是必填的',
        'parent_ids.required' => 'parent_ids是必填的',
        'id.not_exists' => '该资源还有子资源不能被删除',
    ];
    protected $rules = [
        ValidatorInterface::RULE_CREATE => [
            'name' => 'required|unique:permissions',
            'display_name' => 'required',
            'parent_id' => 'required',
            'parent_ids' => 'required',
        ],
        ValidatorInterface::RULE_UPDATE => [
            'name' => 'required|unique:permissions,name,{id}',
            'display_name' => 'required',
            'parent_id' => 'required',
            'parent_ids' => 'required',
        ],
        'DELETE'=>[
            'id' =>'not_exists:permissions,parent_id',
        ]
   ];

    public function callBackGetRules(array $rules){
        $result=[];
        $value_change = array('{id}'=>Input::get('id'));
        foreach ($rules as $key=>$value){
            if(is_string($value) && str_contains($value,'{id}')){
                $result[$key]=strtr($value,$value_change);
            }else{
                $result[$key]=$value;
            }
        }
        return $result;
    }
}
